package thread_01;
class MyBlockingQueue{
    private String[] elems = null;
    private volatile int head = 0;
    private volatile int tail = 0;
    private volatile int size = 0;
//    循环队列
//    记录两个下标，队首，队尾
//    再映引入队列元素个数，区分队满/空
    public MyBlockingQueue(int capacity){
        elems = new String[capacity];
    }
    void put(String elem) throws InterruptedException {
        synchronized (this){
            if (size >= elems.length){
//          队满，后续再处理阻塞的情况
//                用wait阻塞等待
//                前后两个this要一致，
                this.wait();
//                return;
            }
            elems[tail] = elem;
            tail++;
            if (tail >= elems.length){
//            到达末尾，就回到开头
                tail = 0;
            }
//        更新size的值
            size++;

//            唤醒下面take阻塞的等待
            this.notify();
        }
    }

    String take() throws InterruptedException {
        synchronized (this){
            if (size == 0){
//            队列空了
                this.wait();
//                return null;
            }
//        取出head指向的元素
            String result = elems[head];
            head++;
            if (head >= elems.length){
                head = 0;
            }
            size--;
//            take 成功一个元素，就唤醒上面put中的wait操作
            this.notify();
            return result;
        }
    }
}
public class Demo31 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
//      生产者
        Thread t1 = new Thread(() ->{
            try {
                int count = 1;
                while(true){
                    queue.put(count + "");
                    System.out.println("生产："+count);
                    count++;
                    Thread.sleep(1000);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
//      消费者
        Thread t2 = new Thread(() ->{
            try {
                while (true){
                    String result = queue.take();
                    System.out.println("消费："+result);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();
    }
}
